package com.demo.common.controller;

import java.util.Date;

import com.demo.common.model.Blog;
import com.demo.interceptor.ActionInterceptor;
import com.demo.interceptor.ControllerIterceptor;
import com.demo.interceptor.GobalIterceptor;
import com.demo.validator.FormValidator;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;


@Before(ControllerIterceptor.class)//Controller级别拦截器定义
public class BlogController extends Controller {
	public void index() {   
		setAttr("blogs", Blog.me.find("select * from blog"));
		render("index.jsp");
	}
	//可以
	
	@Before(ActionInterceptor.class)//Action级别拦截器定义
	public void form(){
		Integer id=getParaToInt("id");
		if(id!=null&&id>0){
			setAttr("blog", Blog.me.findById(id));
		}
		render("form.jsp");
	}
	@Before(FormValidator.class)//校验器
	public void save(){
		UploadFile file=getFile("img");//非常重要，一定要先取出文件，否则取不到参数值
		Blog blog = getModel(Blog.class,"blog");//"blog"是别名，如果换成b，JSP表里的控件名全要换成b。如果用 getModel(Blog.class),form.jsp里就直接title，不用blog.title
		if(blog.get("id")==null){					
			blog.set("publishTime", new Date());
			blog.save();
		}else if(blog.getInt("id")>0){
			blog.update();
			
		}
		index();
	}
	
	public void delete(){
		Integer id=getParaToInt("id");
		if(id!=null&&id>0){
			boolean flag=Blog.me.deleteById(id);
			if (flag==false){
				renderText("删除失败");
				return;
			}
		}else{
			renderText("删除成功");
			return;
		}
		index();
	}
	

	@Clear({GobalIterceptor.class,ControllerIterceptor.class})  //清除指定的拦截器，不加参数则清除所有
	public void clear(){
		System.out.println("clear interceptor....");
		renderText("no interceptor");
	}

}
